package com.siashan.toolkit.sms.qiniu.core;

import com.qiniu.http.Response;
import com.qiniu.sms.SmsManager;
import com.qiniu.util.Auth;
import com.siashan.toolkit.sms.core.entity.*;
import com.siashan.toolkit.sms.core.executor.AbstractSmsSendExecutor;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

/**
 * 七牛云短信通知执行器
 *
 * @author siashan
 * @since v1.0.1
 **/
@Slf4j
public class QiniuSmsSendExecutor extends AbstractSmsSendExecutor {

    /**
     * 短信客户端
     */
    private final SmsManager smsManager;


    /**
     * 七牛云短信配置
     */
    private QiniuSmsConfig qiniuSmsConfig;

    /**
     * 构造七牛云短信发送处理
     *
     * @param config 七牛云短信配置
     */
    public QiniuSmsSendExecutor(QiniuSmsConfig config) {
        super(config);
        this.qiniuSmsConfig = config;
        Auth auth = Auth.create(config.getAccessKey(), config.getSecretKey());
        smsManager = new SmsManager(auth);
    }

    /**
     * 构造七牛云短信发送处理
     *
     * @param config 七牛云短信配置
     */
    public QiniuSmsSendExecutor(QiniuSmsConfig config,Map<String, SmsTemplate> templateMap) {
        this(config);
        this.templateMap = templateMap;
    }

    /**
     * 构造七牛云短信发送处理
     *
     * @param config 七牛云短信配置
     */
    public QiniuSmsSendExecutor(QiniuSmsConfig config,Map<String, SmsTemplate> templateMap,SmsWhiteList whiteList) {
        this(config,templateMap);
        this.whiteList = whiteList;
    }

    /**
     * 构造七牛云短信发送处理
     *
     * @param config 七牛云短信配置
     */
    public QiniuSmsSendExecutor(QiniuSmsConfig config,Map<String, SmsTemplate> templateMap,SmsWhiteList whiteList,SmsFrequencyLimitConfig frequencyLimit) {
        this(config,templateMap,whiteList);
        this.frequencyLimit = frequencyLimit;
    }


    /**
     * 发送批量通知
     *
     * @param smsSendModel 通知参数
     * @return 是否发送成功
     */
    @Override
    public boolean doSend(SmsModel smsSendModel) {
        try {
            Response response = smsManager.sendMessage(smsSendModel.getTemplateId(), smsSendModel.getPhones().toArray(new String[]{}), smsSendModel.getParams());

            if (!response.isOK()) {
                log.debug("send fail, error: {}", response.error);
                return false;
            }
            return true;
        } catch (Exception e) {
            log.debug(e.getLocalizedMessage(), e);
        }

        return false;
    }

    /**
     * 获取通道
     *
     * @return 通道
     */
    @Override
    public SmsChannel getChannel() {
        return SmsChannel.QINIU;
    }

}
